import java.util.LinkedList;
import java.util.List;

/**
 * 22. 括号生成
 * https://leetcode.cn/problems/generate-parentheses/description/
 */
class Solution {
    List<String> ret;
    StringBuilder path;
    int left, right, n;
    public List<String> generateParenthesis(int _n) {
        left = 0; right = 0; n = _n;
        ret = new LinkedList<>();
        path = new StringBuilder();
        dfs();
        return ret;
    }

    public void dfs() {
        if(right == n) {
            ret.add(new String(path));
            return;
        }

        if(left < n) {
            path.append("(");
            left++;
            dfs();
            left--;
            path.deleteCharAt(path.length() - 1);
        }
        
        if(right < left) {
            path.append(")");
            right++;
            dfs();
            right--;
            path.deleteCharAt(path.length() - 1);
        }

    }
}